/*	
 * Authors: Ken YANG <spng.yang@gmail.com>
 * 	
 * Introduction
 * Do certain "buffer stuffs", see details below
 *
 * Copyright (C) 2007-2008 Ken YANG
 * This program is free software; you can redistribute it and/or 
 * modify it under the terms of the GNU General Public License 
 * as published by the Free Software Foundation, version 2. 
 * THIS SOFTWARE COMES "AS IS" WITHOUT ANY WARRANTIES.
 */

#include "mmh.h"

/*
 * Name: mmh_buffers_alloc()
 *
 * Description: 
 * Allocate send/receive buffers, and set socket rcv/snd 
 * buffers
 *
 * Parameters: 
 * sockfd: Socket fd to set options
 *
 * Return Values: 
 * None
 *
 * */
void 
mmh_buffers_alloc(int sockfd)
{
	int optvalue;
	socklen_t optlen;

	/* Allocate read/write buffer */
	if(mmh_rbuf==NULL)
		mmh_rbuf=Malloc(mmh_rsize);
	if(mmh_wbuf==NULL)
		mmh_wbuf=Malloc(mmh_wsize);

	/* 
	 * Set the socket send and receive buffer size (if 
	 * specified). The receive buffer size is tied to 
	 * the TCP's advertised window.
	 * */

	if(mmh_rcvbuf_size){
		Setsockopt(sockfd,SOL_SOCKET,SO_RCVBUF,
				&mmh_rcvbuf_size,sizeof(mmh_rcvbuf_size));
		optlen=sizeof(optvalue);
		Getsockopt(sockfd,SOL_SOCKET,SO_RCVBUF,&optvalue,&optlen);
		if(optvalue!=mmh_rcvbuf_size)
			err_quit("SO_RCVBUF=%d, but you specified: %d",optvalue ,mmh_rcvbuf_size);
		if(mmh_verbose)
			err_msg("SO_RCVBUF = %d",optvalue);
	}

	if(mmh_sndbuf_size){
		Setsockopt(sockfd,SOL_SOCKET,SO_SNDBUF,
				&mmh_sndbuf_size,sizeof(mmh_sndbuf_size));
		optlen=sizeof(optvalue);
		Getsockopt(sockfd,SOL_SOCKET,SO_SNDBUF,&optvalue,&optlen);
		if(optvalue!=mmh_sndbuf_size)
			err_quit("SO_SNDBUF=%d, but you specified: %d",optvalue ,mmh_sndbuf_size);
		if(mmh_verbose)
			err_msg("SO_SNDBUF = %d",optvalue);
	}
}


